package com.mocaris.android.gank.view.wanandroid


import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout

import com.mocaris.android.gank.R
import com.mocaris.android.gank.adapter.SystreeAdapter
import com.mocaris.android.gank.data.LiveDataResouce
import com.mocaris.android.gank.model.SystemTree
import com.mocaris.android.gank.vm.AndroidMainViewModel
import kotlinx.android.synthetic.main.fragment_system_tree.*


/**
 *知识体系
 */
class SystemTreeFragment : Fragment(), SwipeRefreshLayout.OnRefreshListener,
    Observer<LiveDataResouce<List<SystemTree>>> {

    private lateinit var systreeAdapter: SystreeAdapter
    private lateinit var viewModel: AndroidMainViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {

        }
        viewModel = ViewModelProviders.of(this).get(AndroidMainViewModel::class.java)
        systreeAdapter = SystreeAdapter(activity!!)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_system_tree, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel.systemTree.observe(this, this)
        srl_sys.setOnRefreshListener(this)
        elv_systree.setAdapter(systreeAdapter)
        onRefresh()
    }

    override fun onRefresh() {
        viewModel.getSysTree()
    }

    override fun onChanged(t: LiveDataResouce<List<SystemTree>>) {
        srl_sys?.isRefreshing = false
        if (t.result) {
            systreeAdapter.data = t.data!! as ArrayList<SystemTree>
        }
    }

    companion object {

        @JvmStatic
        fun newInstance() =
            SystemTreeFragment().apply {
                arguments = Bundle().apply {

                }
            }
    }
}
